// gs app
var $gs = {};

/**
 * 按条件下载文件
 * options:{
 *   url:'http://www', //请求的url
 *   data:{sc:'xxx'}//要发送的数据
 * });
 */
$gs.downloadFile = function (options) {
    var config = $.extend(true, {method: 'post'}, options);
    var $iframe = $('<iframe id="down-file-iframe" />');
    var $form = $('<form target="down-file-iframe" method="' + config.method + '" action="' + config.url + '" />');
    for (var key in config.data) {
        $form.append('<input type="hidden" name="' + key + '" value="' + config.data[key] + '" />');
    }
    $iframe.append($form);
    $(document.body).append($iframe);
    $form[0].submit();
    $iframe.remove();
}

/**
 *  清除被easyui动态生成的dialog
 * @param opts
 */
$gs.cleanupExtraDialogs = function (opts) {
    var workspace = $('#workspace');

    // 当新加一个tab时会有额外的div被append到body的最后
    $gs.locateLastPanel = $gs.locateLastPanel || function () {
            $gs.lastPanelUnderBody = $(document.body).children(':last');
        };
    $gs.clearPanel = $gs.clearPanel || function (title) {
            $gs.appendedPanels[title].panel('clear');
            $gs.appendedPanels[title].remove();
            $gs.locateLastPanel();
        }
    $gs.locateLastPanel();
    $gs.appendedPanels = $gs.appendedPanels || {};
    opts = $.extend(opts, {
        onClose: function (title, index) {
            // 切换tab会调这里的onClose,
            // 在切换回该tab时会将之前tab内相关表单新append到body下的dom清掉然后重新生成(如果在这里清楚所有的新加项会导致该步骤报错)。
            // 在这里要做的是清除不在tab内的(如dialog)相关生成项去掉，之后会重新生成
            $gs.clearPanel(opts.title);
            // console.info('opts.onClose:' + opts.title);
        },
        loader: function (queryParams, callback) {
            // hook the loader calling just after panel('clear'), PLEASE DONOT MODIFY
            var th = this;
            $gs.rawPanelOptions = $gs.rawPanelOptions || $('<div/>').panel().panel("options");
            // jquery.easyui.min.js:formatted #3645
            $gs.rawPanelOptions.loader.call(th, queryParams, callback);
            $gs.locateLastPanel();
            // console.info($gs.rawPanelOptions);
        }
    });

    // 全局的，关闭tab只能在这里事件处理
    !$(workspace).tabs('options').name && $(workspace).tabs({
        name: 'workspace',
        onLoad: function (panel) {
            var title = panel.panel('options').title,
                lastPanel = $gs.lastPanelUnderBody,
                filteredWindows = lastPanel.nextAll('.window');
            filteredWindows = filteredWindows.add(lastPanel.nextAll('.window-shadow'));
            $gs.appendedPanels[title] = filteredWindows;
            // console.info('workspace.onLoad:' + title);
        },
        onClose: function (title, index) {
            // 关闭tab会调这里的onClose
            $gs.clearPanel(title);
            // console.info('workspace.onClose:' + title);
        }
    });
}

/**
 * add format for console output
 */
$gs.bindDatePrefixWhenConsoleOut = function () {
    var buildParams = function (args, hasFormat) {
        var params = [];
        params.push('%c[%s]%c %c%s' + (hasFormat ? args[0] : ''));
        params.push('color: blue; font-size: 14px;');
        params.push(new Date().toISOString());
        params.push('');
        params.push('background: yellow; font-size: 14px;');
        for (var i = (hasFormat ? 1 : 0); i < args.length; ++i) {
            params.push(args[i]);
        }
        return params;
    };
    ['trace'].forEach(function (methodname) {
        var rawMethod = console[methodname];
        console[methodname] = function () {
            if (arguments.length > 1 && ['%s', '%d', '%i', '%f', '%o', '%c'].some(function (i) {
                    return arguments[0].indexOf(i) != -1
                })) {
                return rawMethod.apply(console, buildParams(arguments, true));
            }
            return rawMethod.apply(console, buildParams(arguments));
        }
    });
}
$gs.bindDatePrefixWhenConsoleOut();

/**
 * validate parameters to post
 * prune empty string param with none field & toast tip for wrong date foramt.
 * valid parameter object returned if no invalid parameters.
 */
$gs.isValidParam = function (rawParam) {
    var param = {};
    $.each(rawParam, function (key, val) {
        if (val.length && (key == 'startTime' || key == 'endTime')) {
            if (!isDateTime.call(val, 'yyyy/MM/dd')) {
                layer.msg('时间格式错误');
                param = false;
            }
        }
        if (val.length && !/\s/.test(val)) {
            param[key] = val;
        }
    });

    // 时间起止时间校验
    if (param.startTime && param.endTime &&
        param.startTime.length && param.endTime.length &&
        Date.parse(param.startTime) > Date.parse(param.endTime)) {
        layer.msg('结束时间必须大于开始时间');
        param = false;
    }

    return param;
}

/**
 * 初始化页面, 局部作用域
 */
$gs.initView = function (name, initFunc, postInit) {
    $(document).ready(function () {
        var init = initFunc, post = postInit;
        $.isFunction(name) && (init = name, post = initFunc);
        var events = {};
        $.isFunction(init) && init(events);
        $gs['initClickEvents'].call(this, events);
        $.isFunction(post) && post(events);
        $gs.views = $gs.views || {};
        setTimeout(function () {
            !$gs.views[name] && ($gs.views[name] = $('#mainWorkspace').children());
        }, 1000);
    })
}

/**
 * custorm event binding using 'click-event' attribute on <a>
 */
$gs.initClickEvents = function (events) {
    for (var evt in events) {
        if (evt.startsWith('init')) {
            // console.info(evt + ':init');
            events[evt].apply($('[event=' + evt + ']'));
        } else {
            $('[event=' + evt + ']').click((function (cur) {
                return function () {
                    events[cur].call(this, arguments)
                }
            })(evt));
        }
    }
}

/**
 * load html if the
 * @param content
 */
$gs.easyHtml = function (selector, viewUrl, loaded) {
    ($.get(viewUrl, function (r) {
        // remove the easyui element appended by parsing
        $('footer').nextAll().remove();
        // parse easy ui element
        $.parser.parse($(selector).html(r));
        loaded && loaded.apply($(selector), arguments);
    }))
}
/**
 * resolve easydatebox placeholder
 * @author feng.yuan on 2016-7-8
 */
$gs.resolveDateboxPlaceholder = function () {
    setTimeout(function () {
        $('input[textboxname*=Time]').each(function (index, item) {
            $(item).datebox('textbox').attr('placeholder', $(item).attr('placeholder'));
        });
    }, 10);
}

/**
 * get the unique checked row data
 *
 */
$gs.uniqueRowData = function (datagrid) {
    var row = $(datagrid).datagrid('getSelected');
    var rows = $(datagrid).datagrid('getChecked');
    if (!row || rows.length > 1) {
        layer.msg(!row ? '必须选择一行!' : '只能选择一行!');
        return false;
    }

    return row;
}

/**
 * get the multi checked rows' data
 *
 */
$gs.multiRowData = function (datagrid) {
    var rows = $(datagrid).datagrid('getChecked');
    if (!rows.length) {
        layer.msg('必须至少选择一行!');
        return false;
    }

    return rows;
}

/**
 * toggle dialog by specifying attribute 'action'
 *
 */
$gs.toggleDialog = function (dlgSelector, title, actions) {
    var dlg = $(dlgSelector), options = {}, openDlg = true;
    dlg.form('clear');
    $(this).attr('action').split('|').map(function (action) {
        options[action] = !0;
    })
    for (var action in options) {
        // 只支持两个选项,open|close占一个
        if (action == 'open' || action == 'close') {
            continue;
        }
        if ($.isFunction(actions[action])) {
            openDlg = actions[action].apply($(this), dlg) && openDlg;
            break;
        }
    }
    if (openDlg && options.open) {
        if ($.isFunction(actions.open)) {
            dlg.dialog({
                onOpen: actions.open.bind($(this), dlg)
            });
        }
        if ($.isFunction(actions.close)) {
            dlg.dialog({
                onClose: actions.close.bind($(this), dlg)
            });
        }
        dlg.dialog("setTitle", title).dialog("center").dialog("open");
    } else {
        dlg.dialog("close");
    }
    return dlg;
}